package demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;

/*
 * Created by IntelliJ IDEA.
 * 这个类用来对user表进行
 */
public class UserMapper {
    public int insert(User user) {
        try (Connection conn = DBUtil.getConnection();) {
            String sql = "INSERT INTO user(username,password,nickname,age) " +
                    "VALUES(?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.setInt(4, user.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;

    }

    /*
     * 根据用户名查询用户
     * 如果用户名不存在则返回null
     */
    public User selectByUsername(String username) {
        try (Connection connection = DBUtil.getConnection();) {
            String sql = "SELECT id,username,password,nickname,age"+
                    "FROM user"+
                    "WHERE username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setNickname(rs.getString("nickname"));
                user.setAge(rs.getInt("age"));
                return user;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }
}
